package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDTO;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vo.AdUserVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;

import com.heima.utils.common.AppJwtUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * 登录用户
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDTO dto) {
        String name = dto.getName();
        String password = dto.getPassword();
        //检验密码是否输入
        if (StringUtils.isBlank(name) || StringUtils.isBlank(password)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID,"参数错误");
        }
        //查询用户信息
        AdUser adUser = this.getOne(Wrappers.<AdUser>lambdaQuery().eq(AdUser::getName, name));
        // 用户是否存在
        if (adUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"用户名或密码错误");
        }
        //状态判断
        if (9!=adUser.getStatus().intValue()) {
            CustException.cust(AppHttpCodeEnum.LOGIN_STATUS_ERROR,"用户状态异常");
        }
        // 生成密码
        String newPwd = DigestUtils.md5DigestAsHex((password + adUser.getSalt()).getBytes());
        //检验密码是否正确
        if (!adUser.getPassword().equals(newPwd)) {
            CustException.cust(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Map map = new HashMap<>();
        adUser.setLoginTime(new Date());
        //修改时间
        this.updateById(adUser);
        String token = AppJwtUtil.getToken(Long.valueOf(adUser.getId()));

        AdUserVO userVO = new AdUserVO();
        // 用户敏感信息变为null
        BeanUtils.copyProperties(adUser, userVO);

        map.put("token", token);
        map.put("user", userVO);
        return ResponseResult.okResult(map);
    }
}
